from flask import Flask, request, jsonify
import requests
import json
import base64
import uuid
from gevent.wsgi import WSGIServer
app = Flask(__name__)


def get_token(form):
    print(form)
    assert 'appid' in form
    assert 'secret' in form
    app_id = form['appid']
    app_secret = form['secret']

    print("appId: {}, appSecret: {}".format(app_id, app_secret))
    return jsonify({
        "errcode": "T1010",
        "errmsg": "get token success",
        "token": "123456789",
        "expires_time": "7200"
    })


def http_json_get_request(form):
    print(form)
    url = form['url']
    headers = form['header']
    print(headers)
    print(url)
    json_header = json.loads(headers)
    print(json_header)
    resp = requests.get(url, headers=json_header)
    print(resp.headers)
    print(resp.content)
    print(base64.b64encode(resp.content))
    return jsonify({
        "errcode": "0",
        "errmsg": "httprequest success",
        "header": [dict(resp.headers)],
        "content": base64.b64encode(resp.content).decode("utf-8")
    })


def http_json_post_request_by_stream(form):
    print(form)
    url = form['url']
    headers = form['header']
    content = form['content']
    print(headers)
    print(url)
    print(content)
    resp = requests.post(url, headers=json.loads(headers), json=json.loads(content))
    print(resp.content)
    print(base64.b64encode(resp.content))
    return jsonify({
        "errcode": "0",
        "errmsg": "httprequest success",
        "header": [dict(resp.headers)],
        "content": base64.b64encode(resp.content).decode("utf-8")
    })


@app.route('/TokenWechat/webservice.do', methods=['POST'])
def web_service():
    action = request.args.get('action')
    print(action)
    if action == 'getToken':
        print("go to get token")
        return get_token(request.form)
    elif action == 'httpJsonGetRequest':
        print("do httpJsonGetRequest")
        return http_json_get_request(request.form)
    elif action == 'httpJsonPostRequestByStream':
        print("do httpJsonPostRequestByStream")
        return http_json_post_request_by_stream(request.form)
    else:
        return jsonify({
            'errcode': 'T0001',
            'errmsg': "action {} 不存在".format(action)
        })


@app.route('/services/message/lxsend.do', methods=['post'])
def lx_send():
    action = request.args.get('action')
    print("action", action)
    print("json", request.get_json())
    return jsonify({
        'errcode': '0',
        'errmsg': '请求成功'
    })


@app.route('/services/userInfo', methods=['get'])
def user_info():
    action = request.args.get('action')
    print(action)
    if action == 'getUserInfoById':
        return jsonify({
            'errcode': 'U1999',
            'errmsg': 'Success',
            'data': {
                "NAME": "XXXX",
                "POLICENUM": str(uuid.uuid4()).replace('-', '')[:20],
                "DUTY": "XXXX",
                "EMAIL": "XXXX@XXXX",
                "MOBILE_LONG_YIDONG": "0000",
                "MOBILE_LONG_DIANXIN": "0000",
                "MOBILE_OTHER": "0000",
                "MOBILE_SHORT_YIDONG": "0000",
                "MOBILE_SHORT_DIANXIN": "0000",
                "MOBILENUMBER": "0000",
                "MOBILESHORT": "0000",
                "IDCARD": str(uuid.uuid4()).replace('-', '')[:18],
                "DEPTID": "000000000000",
                "ALIAS": "苏州市局科信处",
                "DEPTNAME": "科技信息化处",
                "FULL_NAME": "江苏省苏州市公安局科技信息化处",
                "GENDER": "1",
                "UPDATETIME": "20151123175116",
                "M_USERID": "0000"
            }
        })
    return jsonify({
        'errcode': 'U1999',
        'errmsg': 'Success',
        'data': {}
    })


if __name__ == '__main__':
    print('Starting Application ...')
    http_server = WSGIServer(('', 5000), app)
    http_server.serve_forever()
